'use strict';

const crypto = require('crypto');

exports.main = async (event, context) => {
  console.log('[LOG] 收到微信消息推送请求:', JSON.stringify(event, null, 2));
  
  try {
    // 处理GET请求（验证服务器）
    if (event.httpMethod === 'GET') {
      return handleServerVerification(event);
    }
    
    // 处理POST请求（接收消息推送）
    if (event.httpMethod === 'POST') {
      return await handleMessagePush(event);
    }
    
    return {
      statusCode: 405,
      body: 'Method Not Allowed'
    };
    
  } catch (error) {
    console.error('[ERROR] 处理微信消息推送失败:', error);
    return {
      statusCode: 500,
      body: 'Internal Server Error'
    };
  }
};

// 处理服务器验证（GET请求）
function handleServerVerification(event) {
  console.log('[LOG] 处理服务器验证请求');
  
  const { signature, timestamp, nonce, echostr } = event.queryStringParameters || {};
  
  if (!signature || !timestamp || !nonce || !echostr) {
    console.error('[ERROR] 验证参数不完整');
    return {
      statusCode: 400,
      body: 'Bad Request: Missing parameters'
    };
  }
  
  // 获取Token（从环境变量或配置中获取）
  const token = 'zhentou_wechat_token_2024'; // 这个需要与微信后台配置一致
  
  // 验证签名
  const tmpArr = [token, timestamp, nonce].sort();
  const tmpStr = tmpArr.join('');
  const tmpSignature = crypto.createHash('sha1').update(tmpStr).digest('hex');
  
  if (tmpSignature === signature) {
    console.log('[LOG] 服务器验证成功');
    return {
      statusCode: 200,
      body: echostr
    };
  } else {
    console.error('[ERROR] 服务器验证失败');
    return {
      statusCode: 403,
      body: 'Forbidden: Invalid signature'
    };
  }
}

// 处理消息推送（POST请求）
async function handleMessagePush(event) {
  console.log('[LOG] 处理消息推送请求');
  
  const { msg_signature, timestamp, nonce } = event.queryStringParameters || {};
  
  if (!msg_signature || !timestamp || !nonce) {
    console.error('[ERROR] 推送参数不完整');
    return {
      statusCode: 400,
      body: 'Bad Request: Missing parameters'
    };
  }
  
  try {
    // 解析请求体
    let requestBody;
    if (typeof event.body === 'string') {
      requestBody = JSON.parse(event.body);
    } else {
      requestBody = event.body;
    }
    
    console.log('[LOG] 请求体:', JSON.stringify(requestBody, null, 2));
    
    const { Encrypt } = requestBody;
    if (!Encrypt) {
      console.error('[ERROR] 缺少加密消息体');
      return {
        statusCode: 400,
        body: 'Bad Request: Missing Encrypt field'
      };
    }
    
    // 验证消息签名
    const token = 'zhentou_wechat_token_2024';
    if (!verifyMessageSignature(token, timestamp, nonce, Encrypt, msg_signature)) {
      console.error('[ERROR] 消息签名验证失败');
      return {
        statusCode: 403,
        body: 'Forbidden: Invalid message signature'
      };
    }
    
    // 解密消息
    const decryptedMessage = decryptMessage(Encrypt);
    console.log('[LOG] 解密后的消息:', JSON.stringify(decryptedMessage, null, 2));
    
    // 处理不同类型的消息
    const response = await processMessage(decryptedMessage);
    
    // 如果需要回复消息，进行加密
    if (response && response !== 'success') {
      const encryptedResponse = encryptMessage(JSON.stringify(response));
      return {
        statusCode: 200,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(encryptedResponse)
      };
    }
    
    // 默认回复success
    return {
      statusCode: 200,
      body: 'success'
    };
    
  } catch (error) {
    console.error('[ERROR] 处理消息推送异常:', error);
    return {
      statusCode: 200,
      body: 'success' // 即使处理失败也要返回success，避免微信重复推送
    };
  }
}

// 验证消息签名
function verifyMessageSignature(token, timestamp, nonce, encrypt, signature) {
  const tmpArr = [token, timestamp, nonce, encrypt].sort();
  const tmpStr = tmpArr.join('');
  const tmpSignature = crypto.createHash('sha1').update(tmpStr).digest('hex');
  return tmpSignature === signature;
}

// 解密消息
function decryptMessage(encryptedMsg) {
  try {
    // 这里需要实现AES解密逻辑
    // 由于解密逻辑比较复杂，先返回模拟数据用于测试
    console.log('[DEBUG] 解密消息（当前为模拟实现）');
    
    // 模拟解密后的合作店铺订单通知
    return {
      ToUserName: "gh_2defbb026678",
      FromUserName: "OPENID",
      CreateTime: Math.floor(Date.now() / 1000),
      MsgType: "event",
      Event: "cooperation_shop_order",
      Data: {
        order_id: "test_order_" + Date.now(),
        shop_appid: "test_shop_appid"
      }
    };
  } catch (error) {
    console.error('[ERROR] 解密消息失败:', error);
    throw error;
  }
}

// 加密回复消息
function encryptMessage(message) {
  try {
    // 这里需要实现AES加密逻辑
    // 由于加密逻辑比较复杂，先返回简单格式
    console.log('[DEBUG] 加密回复消息（当前为模拟实现）');
    
    const timestamp = Math.floor(Date.now() / 1000);
    const nonce = Math.random().toString(36).substr(2, 15);
    
    return {
      Encrypt: "encrypted_message_placeholder",
      MsgSignature: "signature_placeholder",
      TimeStamp: timestamp,
      Nonce: nonce
    };
  } catch (error) {
    console.error('[ERROR] 加密回复消息失败:', error);
    throw error;
  }
}

// 处理不同类型的消息
async function processMessage(message) {
  console.log('[LOG] 处理消息类型:', message.MsgType, '事件类型:', message.Event);
  
  try {
    if (message.MsgType === 'event') {
      if (message.Event === 'cooperation_shop_order' || message.Event === 'related_shop_order_submission') {
        // 处理合作店铺订单通知
        return await handleCooperationOrderNotification(message);
      }
    }
    
    console.log('[LOG] 未处理的消息类型，返回success');
    return 'success';
    
  } catch (error) {
    console.error('[ERROR] 处理消息异常:', error);
    return 'success'; // 即使处理失败也返回success
  }
}

// 处理合作店铺订单通知
async function handleCooperationOrderNotification(message) {
  console.log('[LOG] 处理合作店铺订单通知');
  
  try {
    const { Data, FromUserName } = message;
    const { order_id, shop_appid } = Data;
    
    console.log(`[LOG] 订单通知详情: order_id=${order_id}, shop_appid=${shop_appid}, openid=${FromUserName}`);
    
    // 调用order-center云函数处理订单
    const result = await uniCloud.callFunction({
      name: 'order-center',
      data: {
        action: 'handleCooperationOrderNotify',
        shop_appid: shop_appid,
        order_id: order_id,
        openid: FromUserName
      }
    });
    
    console.log('[LOG] 订单处理结果:', JSON.stringify(result, null, 2));
    
    return 'success';
    
  } catch (error) {
    console.error('[ERROR] 处理合作店铺订单通知失败:', error);
    return 'success';
  }
}
